import pymongo
from pymongo import MongoClient

yi = 100000000
wan = 10000


def get_Save_DB():
    url = "192.168.1.99"
    # url = "tit.pub"
    # url = "localhost"
    port = 27017
    db_name = 'comic_spider_db'
    client = MongoClient(url, port)
    client[db_name].authenticate('xmtj', '0-=p[]P{}', 'admin')
    db = client[db_name]
    return db


def get_Spider_DB():
    url = "192.168.1.99"
    # url = "localhost"
    port = 27017
    db_name = 'resultdb'
    client = MongoClient(url, port)
    client[db_name].authenticate('xmtj', '0-=p[]P{}', 'admin')
    db = client[db_name]
    return db


def str2Int(strNum):
    strNum = str(strNum)
    try:
        if strNum.find('亿') != -1:
            return float(strNum.replace('亿', '').replace(',', '')) * yi
        if strNum.find('万') != -1:
            return float(strNum.replace('万', '').replace(',', '')) * wan
        return float(strNum.replace(',', ''))

    except Exception as e:
        print(" Exception:", e, strNum)
    return 0


def get163Score(base_163, ipName):
    l = base_163.find({'title': ipName})
    for o in l:
        score = str2Int(o['like_count'])
        # print('name:', ipName, '  score:', score)
        return score
    # 不存在  return 0 分
    return 0


def getQQScore(base_qq, ipName):
    l = base_qq.find({'title': ipName})
    for o in l:
        like_score = str2Int(o['like_count'])
        read_score = str2Int(o['read_count'])
        # print('name:', ipName, '  like_score:', like_score, '  read_score:', read_score)
        return read_score + like_score
    # 不存在  return 0 分
    return 0


def getU17Score(base_u17, ipName):
    l = base_u17.find({'title': ipName})
    for o in l:
        like_score = str2Int(o['like_count'])
        total_ticket_count = str2Int(o['total_ticket_count'])
        collection_count = str2Int(o['collection_count'])
        # print('name:', ipName, '  like_score:', like_score, '  total_ticket_count:', total_ticket_count,
        #       '  collection_count:', collection_count)
        return total_ticket_count + like_score + collection_count
    # 不存在  return 0 分
    return 0


def getKuaiKanScore(base_kuaikan, ipName):
    l = base_kuaikan.find({'title': ipName})
    for o in l:
        like_score = str2Int(o['like_count'])
        read_count = str2Int(o['read_count'])
        comment_count = str2Int(o['comment_count'])
        # print('name:', ipName, '  like_score:', like_score, '  read_count:', read_count,
        #       '  comment_count:', comment_count)
        return read_count + like_score + comment_count
    # 不存在  return 0 分
    return 0


def getZYMKScore(base_zymk, ipName):
    l = base_zymk.find({'title': ipName})
    for o in l:
        read_count = str2Int(o['read_count'])
        collection_count = str2Int(o['collection_count'])
        gold_count = str2Int(o['gold_count'])
        total_ticket_count = str2Int(o['total_ticket_count'])
        recommend_count = str2Int(o['recommend_count'])
        # print('name:', ipName, '  read_count:', read_count, '  collection_count:', collection_count,
        #       '  gold_count:', gold_count,
        #       '  total_ticket_count:', total_ticket_count,
        #       '  recommend_count:', recommend_count)
        return read_count + collection_count + gold_count + total_ticket_count + recommend_count
    # 不存在  return 0 分
    return 0


def ranking():
    # 排名数据库
    rankDb = get_Save_DB().comic_rank

    spiderDB = get_Spider_DB()
    base_163 = spiderDB.base_163
    base_qq = spiderDB.base_qq
    base_kuaikan = spiderDB.base_kuaikan
    base_u17 = spiderDB.base_u17
    base_zymk = spiderDB.base_zymk

    # 创建排行数据库索引
    rankDb.create_index([('score', pymongo.DESCENDING)])
    # 总漫画数据库
    allIpName = get_Save_DB().all_ip_name

    allName = allIpName.find()
    i = 1
    for ipNameObj in allName:
        ipName = ipNameObj['ip_name']
        ipAuthor = ipNameObj['author']
        # qq 得分
        score_qq = getQQScore(base_qq, ipName)

        # 163 得分
        score_163 = get163Score(base_163, ipName)

        # # u17 得分
        score_u17 = getU17Score(base_u17, ipName)

        # 快看 得分
        score_kuankan = getKuaiKanScore(base_kuaikan, ipName)

        # zymk 得分
        score_zymk = getZYMKScore(base_zymk, ipName)

        total_score = score_qq + score_163 + score_kuankan + score_u17 + score_zymk

        isUpdateSuccess = rankDb.find_one_and_update({'ip_name': ipName},
                                                     {'$set': {'score': total_score, 'author': ipAuthor}}, upsert=True)
        print('更新漫画', ipName, ':', i)
        print('isUpdateSuccess:', isUpdateSuccess)
        i = i + 1
        # if isUpdateSuccess == None:
        #     print('数据库没有此漫画：', ipName)
        #     rankDb.insert({'score': total_score, 'ip_name': ipName, 'author': ipAuthor})

            # scores = rankDb.find({'rank': {'$gte': 80}})
            # print(scores.count())
            # rank = scores.count()
            # print('排名是：', rank)


if __name__ == "__main__":
    ranking()

    # rankDb = get_Save_DB().comic_rank
    # for o in rankDb.find({'ip_name': '测试001'}):
    #     score = o['score']
    #     print("score",score)
    #     rank = rankDb.find({'score': {'$gte': score}}).count()
    #     print('斗破苍穹 排名：', rank)
    #
    # print('--------------')
    # rank = 1
    # for top10 in rankDb.find().sort([('score', pymongo.DESCENDING)]).limit(100):
    #     print(top10['ip_name'], '  :', top10['score'], '排名：', rank)
    #     rank = rank + 1
